#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

#include "log.hpp"

using std::cout;
using std::endl;
using std::vector;
using std::string;
using std::cin;

const int size = 4096;
const char* pathName = "/home/ubuntu";
const int proj_id = 0x33777;

log comlog;

key_t getKey(){
    key_t key = ftok(pathName, size);
    if(key < 0){
        comlog(Fatal, "getKey error,error string: %s, error code: %d", strerror(errno), errno);
        exit(1);
    }
    comlog(Info, "getKey sucess, key = 0x%x", key);
    return key;
}

int getMemory(int flag){
    key_t key = getKey();
    int shmid = shmget(key, size, flag);
    if(shmid < 0){
        comlog(Fatal, "getMemory error,error string: %s, error code: %d", strerror(errno), errno);
        exit(1);
    }
    comlog(Info, "getMemory sucess, shmid = %d", shmid);
    return shmid;
}

int createShm(){
    return getMemory(IPC_CREAT | IPC_EXCL | 0666);
}

int getShm(){
    return getMemory(IPC_CREAT);
}

// 命名管道
#define FILEPATH "./pipe"
#define FILEMODE 0664

struct mypipe{
    mypipe(){
        int n = mkfifo(FILEPATH, FILEMODE);
        if(n == -1){
            perror("mkfifo");
            exit(1);
        }
    }
    ~mypipe(){
        int n = unlink(FILEPATH);
        if(n == -1){
            perror("unlink");
            exit(2);
        }
    }
};
